<?php

namespace Common\Service;
use Think\Model\MongoModel;

Class BaseService extends MongoModel {

    protected $connection;
    protected $pk           = 'id';
    protected $_idType      = self::TYPE_INT;
    protected $autoinc      =  true;         // $_autoinc 无效 
    protected $dbName       = 'imba';
    protected $tablePrefix  = 'imba_';  
    // protected $autoCheckFields = true;

    public function __construct($name='',$tablePrefix='',$connection='') {
        $this->connection = array(
            'db_type'       => 'mongo',
            'db_host'       => C('MONGODB_HOST', null, 'localhost'),#
            'db_port'       => C('MONGODB_PORT', null, 27017),
            'db_name'       => C('MONGODB_DB', null,''),
            'db_charset'    => 'utf8',
            'db_user'       => C('MONGODB_USERNAME', null, ''),
            'db_prefix'     => C('MONGODB_PREFIX', null, ''),
            'db_pwd'        => C('MONGODB_PASSWORD', null, ''),
        );
        parent::__construct($name,$tablePrefix, $this->connection);
    }
    /** 
     * 统计项目
     * @author Legend. <xcx_legender@qq.com>
     * @param $match 条件 $group 分组字段 $sum 统计字段
     * @return 
     */
    
    protected function _before_update(&$data,$options){
        if (!empty($data['_id'])){
            unset($data['_id']);
        }
        if (!empty($data['id'])){
            unset($data['id']);
        }
    }
    
    public function total($match, $group, $sum, $sort = [], $limit = 0)
    {
    	$options = array();
    	$match && $options[]['$match'] = $match;
    	$options[]['$group'] = array(  
		            '_id'  =>  '$'.$group,  
		           'count' => array('$sum' => 1),  
		           'sum'   => array('$sum' => '$'.$sum),  
		        );
    	$options[]['$project'] = array(
		        	$group =>'$_id', 
		        	'total'=>'$sum',
		        	'count'=>'$count',
		        	'_id' => 0);
        if ($sort && is_array($sort)) {
            $options[]['$sort'] = $sort;
        }
        $limit && $options[]['$limit'] = $limit;
		return $this->aggregate($options);
    }

    public function aggregate($options)
    {
        $this->_after_db();
    	$res = $this->db->aggregate($options);
        return $res['result'];
    }

    /*public function add($data='',$options=array(),$replace=false)
    {
        if(empty($data)) {
            // 没有传递数据，获取当前数据对象的值
            if(!empty($this->data)) {
                $data           =   $this->data;
                // 重置数据
                $this->data     = array();
            }else{
                $this->error    = L('_DATA_TYPE_INVALID_');
                return false;
            }
        }
        // 分析表达式
        $options    =   $this->_parseOptions($options);
        // 数据处理
        $data       =   $this->_facade($data);
        if(false === $this->_before_insert($data,$options)) {
            return false;
        }
        // 写入数据到数据库
        $result = $this->db->insert($data,$options,$replace);
        if(false !== $result ) {
            $insertId   =   $data[$this->getPk()];
            // if($insertId) {
            //     // 自增主键返回插入ID
            //     // $data[$this->getPk()]  = $insertId;
            //     $this->_after_insert($data,$options);
            //     return $insertId;
            // }
            return $insertId;
            $this->_after_insert($data,$options);
        }
        return $result;
    }*/


    // 查询单一集合
    public function distinct($key, $query)
    {
        $command = array('distinct'=>$this->getTableName(),'key'=>$key, 'query' => $query);
        $result = $this->db->command($command);
        // $count = COUNT(array_unique($result['values']));
        return $result['values'];
    }


    public function _after_find(&$result,$options)
    {
        if (!empty($result['_id'])){
            // unset($result['_id']);
        }
        foreach ($result as $key => &$value) {
            if (is_string($value)){
                $value = htmlspecialchars_decode($value);
            }
        }
    }

    protected function _after_select(&$resultSet,$options){
        parent::_after_select($resultSet,$options);
        foreach ($resultSet as &$result) {
            $this->_after_find($result, $options);
        }
    }


}